package com.itheima.accountingdb.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.accountingdb.pojo.PageBean;
import com.itheima.accountingdb.pojo.User;
import com.itheima.accountingdb.mapper.UserMapper;
import com.itheima.accountingdb.pojo.UserQuery;
import com.itheima.accountingdb.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


import java.util.List;

/**
 * <p>
 * 用户表，存储用户基本信息 服务实现类
 * </p>
 *
 * @author pww
 * @since 2025-03-06
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public PageBean<User> queryUserPage(UserQuery query) {
        // 边界条件检查
        if (query == null || query.getPageNo() <= 0 || query.getPageSize() <= 0) {
            throw new IllegalArgumentException("Invalid page number or page size");
        }

        PageBean<User> pageBean = new PageBean<>();
        try {
            // 开始分页
            PageHelper.startPage(query.getPageNo(), query.getPageSize());

            // 查询用户列表
            List<User> users = baseMapper.queryUserPage(query);

            // 获取分页信息
            PageInfo<User> pageInfo = new PageInfo<>(users);
            pageBean.setTotal(pageInfo.getTotal());
            pageBean.setPageSize(pageInfo.getPageSize());
            pageBean.setPage(pageInfo.getPageNum());
            pageBean.setItems(pageInfo.getList());

        } catch (Exception e) {
            // 异常处理
            // 记录日志
            log.error("Error occurred while querying user page", e);
            throw new RuntimeException("Failed to query user page", e);
        }

        return pageBean;
    }

}
